package com.chen.web_chat.service.impl;/*
 *classNameLove  HURTS
 *Desciption
 *@Author　yq
 *＠Create 2023/11/21
 *@Version 1.0
 */


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.chen.web_chat.entity.vo.ValidateCodeVo;
import com.chen.web_chat.service.ValidateCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ValidateCodeServiceIml implements ValidateCodeService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 生成图片验证码
     */
    public ValidateCodeVo generateValidateCode() {
        //通过一个工具生成图片验证码 hutool
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 2);
        String codeValue = circleCaptcha.getCode();
        String imageBase64 = circleCaptcha.getImageBase64();

        //把验证码存储到redis里面，设置redis的key: uuid redis的value : 验证码的值 设置过期时间
        String validateCodeKey = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set("webChatUser:validate:" + validateCodeKey,
                codeValue,
                1,
                TimeUnit.MINUTES);

        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setValidateCodeKey(validateCodeKey);
        validateCodeVo.setImageBase64("data:image/png;base64," + imageBase64);

        return validateCodeVo;
    }
}
